#!/usr/bin/perl -Ilibs -I../www/libs

package API::ContentAdmin;

use strict;
use warnings;
use autodie;
use namespace::autoclean;

use Carp;
use Moose;
use MooseX::NonMoose;
use Try::Tiny;
use ECS::CDN::S3;

use API::Controller ();
use ECS::ProductCategory::Attribute;
use ECS::ProductCategory;
use ECS::ContentLandingPage;
use ECS::Site;
use ECS::dbConfig;

extends "API::Controller",
    "SOAP::Server::Parameters";

use API::Config;

has 'site_dbh' => (
        'is'    => "rw",
        'isa'   => "DBI::db",
        'lazy' => 1,
        'builder' => "_build_site_dbh",
    );

has 'site_dbhr' => (
        'is'    => "rw",
        'isa'   => "DBI::db",
        'lazy' => 1,
        'builder' => "_build_site_dbhr",
    );

__PACKAGE__->meta->make_immutable;

###############################################################################

sub _build_site_dbh {
    my $self = shift;
    return ECS::Site->fromName( $self->input->{site})->site_dbh;
}

sub _build_site_dbhr {
    my $self = shift;
    return ECS::Site->fromName( $self->input->{site})->site_dbhr;
}

sub index {
    my $self = shift->new({'input' => shift || {}});

    $self->data->{'templates'} = [ "index.html" ];
    return $self->result;
}

sub getChildCategories {
    my $self = (shift)->new({'input' => shift || {}});

    $self->data->{'dataType'} = "json";

    my $category = ECS::ProductCategory->new({
        'dbh' => $self->site_dbhr,
        'productCategoryID' => $self->input->{'productCategoryID'},
    });

    $self->data->{'data'} = JSON->new->allow_blessed->convert_blessed->encode(\@{$category->childs});

    return $self->result;
}

sub getSelectedCategoryTree {
    my $self = (shift)->new({'input' => shift || {}});

    $self->data->{'dataType'} = "json";

    my $category = ECS::ProductCategory->new({
        'dbh' => $self->site_dbhr,
        'productCategoryID' => $self->input->{productCategoryID},
    });

    my $result = {parents => [], children => {}};

    $result->{parents} = $category->parents;
    foreach my $parent (@{$category->parents}) {
      my $parentCategory = ECS::ProductCategory->new({
          'dbh' => $self->site_dbhr,
          'productCategoryID' => $parent->{productCategoryID},
      });
      $result->{children}->{$parent->{productCategoryID}} = $parentCategory->childs;
    }

    $self->data->{'data'} = JSON->new->allow_blessed->convert_blessed->encode($result);

    return $self->result;
}

sub save {
    my $self = shift->new({ 'input' => shift || {} });
    my $envelope = pop;
    
    my $categoryID = $self->input->{'categoryID'};
    my $brandID = $self->input->{'brandID'};
    my $siteName = $self->input->{ 'site' }
        or croak "Missing siteID";

    my $site;
    try {
        $site = ECS::Site->fromName($siteName)
    }
    catch {
        croak "Invalid siteID: $_";
    };

    my $contentLandingPageID = $self->input->{'contentLandingPageID'};
    my $imageName = $self->input->{'image'};
    my $description = $self->input->{'description'};
    my $h1 = $self->input->{ 'h1' };
    my $title = $self->input->{ 'title' };
    my $canonicalCategoryID = $self->input->{'canonicalCategoryID'};
    my $enabled = $self->input->{'enabled'};
    my $employeeID = $self->input->{ 'employeeID' };

    my $clp = ECS::ContentLandingPage->new({
        'dbh'        => $site->site_dbh,
        'employeeID' => $employeeID,
        ( $contentLandingPageID
            ? ( 'contentLandingPageID' => $contentLandingPageID )
            : ()
        ),
    });

    my $image = try {
        my @parts = $envelope->parts;
        $parts[0]->[0]->bodyhandle->as_string;
    }
        catch { undef };

    my $imagePath = $self->_uploadImage( $image, $imageName );
    $clp->imagePath( $imagePath )
        if $imagePath;

    $clp->categoryID( $categoryID );
    $clp->brandID( $brandID );
    $clp->description( $description );
    $clp->h1( $h1 );
    $clp->title( $title );
    $clp->canonicalCategoryID( $canonicalCategoryID );
    $clp->enabled( $enabled ? "YES" : "NO" );

    if($clp->contentLandingPageID && !$h1 && !$title && !$description){
        $clp->delete;
        $self->data->{'dataType'} = "json";
        $self->data->{'data'} = {}
    } else {
        if( $clp->contentLandingPageID ) {
            $clp->update;
        }
        else {
            $clp->insert;
        }
        $self->data->{'dataType'} = "json";
        $self->data->{'data'} = JSON->new->allow_blessed->convert_blessed->encode($clp);
    }

    return $self->result;
}

sub getLandingPage {
    my $self = shift->new({'input' => shift || {}});

    my $categoryID = $self->input->{'categoryID'};
    my $brandID = $self->input->{'brandID'};
    my $siteName = $self->input->{ 'site' }
        or croak "Missing siteID";
    
    my $site;
    try {
        $site = ECS::Site->fromName($siteName)
    }
    catch {
        croak "Invalid site: $_";
    };

    my %where;

    if($categoryID && !$brandID) {
        $where{categoryID} = $categoryID;
        $where{brandID} = undef;
    }
    elsif($brandID && !$categoryID) {
        $where{brandID} = $brandID;
        $where{categoryID} = undef;
    }
    else {
        $where{brandID} = $brandID;
        $where{categoryID} = $categoryID;
    }

    my $clps = ECS::ContentLandingPage->search({
        'dbh'    => $site->site_dbhr,
        'search' => [
            \%where
        ],
    });
    
    my $clp = $clps->[ 0 ];
    $clp = $clp->pack if $clp;

    if(defined $clp) {
        $self->data->{'dataType'} = "json";
        $self->data->{'data'} = JSON->new->allow_blessed->convert_blessed->encode($clp);
    }
    else {
        $self->data->{'dataType'} = "json";
        $self->data->{'data'} = {};
    }

    return $self->result;
}

sub _uploadImage {
    my ( $self, $image, $imageName ) = @_;

    return unless $image;
    return unless $imageName;



        my $s3 = ECS::CDN::S3->new();
    my $container = 'static';
    
    my $i = 1;
    my $imagePath = "contentLandingPage/$imageName";
    while( 1 ) {
       my $object_name = $s3->build_path( $container => $imagePath );

        # if something is already there, add a number to the name
   eval {
        if( $s3->exists( $object_name ) ) {
            $imagePath = "contentLandingPage/${i}_$imageName";
            $i ++;
            next;
        }
 };

    $s3->post( $object_name, $image );
        last;
    }

    return $imagePath;
}

######################
