package CLMApp::Controller::ChainConcept;
use Mojo::Base 'Mojolicious::Controller';
use Data::Show;
use Moose;
use Moose::Autobox;
use Perl6::Junction qw/any/;
use Data::Show;
use JSON;
use Cwd;
use Digest::MD5 qw(md5 md5_hex md5_base64);
use Digest::SHA1  qw(sha1 sha1_hex sha1_base64);
use Storable 'dclone';
use Class::Tiny qw//, {
	title => 'Chain Concepts',
	table => 'ChainConcept',
	module => 'chainconcept',
	pk => 'chainconceptid',
	columns => [qw/active chainconceptid chainconceptname chainconceptamphireid parentid chaingroupid thresholdtype thresholdvalue arrowstreamid/],
	prefetch => [qw/chaingrp/],
	order_by => ['me.chainconceptname']
};
sub index{
	my $c = shift;
	$c->stash(frm => undef,butt => undef);
	$c->stash(title=> $c->title(),table => $c->module() . 'table' ,module=> $c->module());


	$c->render(template => 'customer/index');
}

sub read {
	my $c = shift;
	
	# show $c->{form};
	my $p = $c->req->params->to_hash;
	if($c->stash($c->pk) eq 'add'){
		return $c->add();
	};
	my @c = $c->db->resultset($c->table)->search({$c->pk=>$c->stash($c->pk)}, 
		{result_class=>'DBIx::Class::ResultClass::HashRefInflator'}
		) or return $c->render(text => 'Record not found.', status => 405);
	# my @c =  [ $c->db->resultset($c->table)->find({$c->pk=>$c->stash($c->pk)})->distributor ]->map(sub {
	# 		my %c = $_->get_columns;
	# 		return \%c;
	# 	});

	my ($frm,$butt) = $c->populate_form('default',$c[0]);

	$c->stash(frm => $frm);
	$c->stash(butt => $butt);

	$c->render(template => 'customer/edit');
	# $c->render(json => $c[0]);
}			
sub add{
	my $c = shift;
	my $p = $c->req->params->to_hash;
	my ($frm,$butt) = $c->populate_form('add',$p);

	$c->stash(frm => $frm);
	$c->stash(butt => $butt);

	$c->render(template => 'customer/edit');

}

sub create {
	my $c = shift;
	my $j = $c->req->params->to_hash;
	delete($j->{$c->pk});
	my $s = $c->db->resultset($c->table)->create($j);
	my $pk = $c->pk;
	my %p = $c->db->resultset($c->table)->find({$c->pk() => $s->$pk})->get_columns;
	$c->render(json => \%p);
}

sub list {
	my $c = shift;
	my $p = $c->req->params->to_hash;

	my $jobj = $c->dtsearch({prefetch => $c->prefetch, params => $p, table=> $c->table, order_by => $c->order_by, sort => 'desc', group_by => [$c->pk], columns => $c->columns});
	return 1 if $jobj == 1;

	$c->render(json => $jobj);
}

sub update{
	my $c = shift;
	my $j = $c->req->params->to_hash;
	$j->{active} = 0 if !exists($j->{active});
	
	if($j->{single}){
		$j->{active} = 0 if !exists($j->{active});
		delete($j->{single});
	}

	my %c = $c->db->resultset($c->table)->find({ $c->pk() => $c->stash($c->pk) })->update($j)->get_columns or return $c->render(text => 'Record not found or cannot update.', status => 405);	
	$c->render(json=>\%c);
}

sub delete{
  my $c = shift;
  my($id) = ($c->stash($c->pk) || $c->param($c->pk));
  $c->db->resultset($c->table)->search({$c->pk() => $id})->delete();
  $c->render(json=>{$c->pk=>$id});
}


sub report{
	my $c = shift;

	$c->stash(frm => undef,butt => undef);
	$c->stash(title=>'Report',table => 'chainconcepttable',module => 'chainconcept');


	$c->render(template => 'customer/report');
}



sub export_threshold {
	my $c = shift;
	# $c->req->param('ssearch', {
	# 	thresholdvalue => { '>' => 0 },

	# });
	my $p = $c->req->params->to_hash;


	if($p->{chaingroups}){
		$p->{export} = 1;
		$p->{csv} = 1;
	}else{
		$p->{export} = 1;
		$p->{csv} = 0;		
	}
	# $p->{csv_seperator} = "\t";

	my $cols = [qw/chaingrp.chaingroupid chaingrp.chaingroupname chaingrp.chaingroupamphireid chainconceptamphireid chainconceptname thresholdvalue/];

	my $headers = [qw/ChainOwnerID ConceptID ChainOwner ChainConcept Threshold/];
	my $excols = [qw/chaingrp.chaingroupamphireid chainconceptamphireid chaingrp.chaingroupname chainconceptname thresholdvalue/];
	if($p->{chaingroups}){
		$headers = [qw/Active ChainITNID ConceptITNID ChainASID ConceptASID Chain Concept DMAVP DMASCS StoreFrontCode Notes/];
		$excols = [qw/chaingrp.active chaingrp.chaingroupamphireid chainconceptamphireid chaingroup.arrowstreamid arrowstreamid chaingrp.chaingroupname chainconceptname chaingrp.chaingroupvp chaingrp.chaingrouppam chaingrp.bpstorefrontcode chaingrp.chaingroupnotes/];
	}
	
	# status.displayorder status.dscr status.id 'status'
	my $join = [qw//];
	my $prefetch = [qw/chaingrp/];
	my $ecols = [];
	my $dt =  DateTime->now(time_zone  => 'America/Chicago');

	my $dtobj = {
		columns => $cols, excolumns => $excols, ecols => $ecols, join => $join, params => $p, table=> 'ChainConcept', order_by => [qw/chaingrp.chaingroupamphireid chainconceptamphireid/], sort => 'asc', group_by => [qw/chaingrp.chaingroupamphireid chainconceptamphireid/], prefetch => $prefetch, defer => 1, 
		exheader => $headers,
		filename => 'ConceptThreshold.xls',
	};
	if($p->{chaingroups}){
		$dtobj->{eheaders} = 1;
		$dtobj->{filename} = 'ConceptThreshold.csv';


	}


	my $jobj = $c->dtsearch($dtobj);
	
	return 1 if $jobj == 1;

	$c->render(json => $jobj);
}

sub setup{
	my $c = shift;


	my $fform = {
		attrs => {
			name => 'chainconceptform',
			onsubmit => 'javascript: return false;',
			title => '',
			action => '',
			method => 'POST',
			formon => 'form-always',
			formoff => 'form-never',
			cols => 1,
			autocomplete=>"new-password"
		},
		sorder => [],
		eorder => [qw/active chaingroupid chainconceptid chainconceptname chainconceptamphireid arrowstreamid thresholdtype thresholdvalue/],
		elems =>     {
			active => {
			      attrs => { class => "", name => "active" },
				  labels => ['Enabled'],			      
				  title => "Active",
			      type => "checkbox",
			      vals => [1],
			      default => undef
			},	
			thresholdtype => {
			      attrs => { class => "form-control input-md", name => "thresholdtype", },
			      default => undef,
			      labels => [qw/Dollars Cases/],
			      title => "Threshold Type", 
			      type => "select",
			      vals => [qw/Dollars Cases/],
			    },	
			thresholdvalue => {
			      attrs => {
			                 class => "form-control input-md",
			                 name => "thresholdvalue",
			                 
			               },
			      title => "Threshold Value",
			      type => "number",
			      val => undef,
			      default => undef
			},				    				
			chainconceptid => {
			      attrs => { class => "form-control input-md", name => "chainconceptid" },
			      title => "ID",
			      type => "hidden",
			      val => undef,
			},
			chainconceptname => {
			      attrs => {
			                 class => "form-control input-md",
			                 name => "chainconceptname",
			                 required => "required",
			               },
			      title => "Name",
			      type => "textfield",
			      val => undef,
			},			
			chainconceptamphireid => {
			      attrs => {
			                 class => "form-control input-md",
			                 name => "chainconceptamphireid",
			                 required => "required",
			               },
			      title => "ITN ID",
			      type => "textfield",
			      val => undef,
			},
			arrowstreamid => {
			      attrs => {
			                 class => "form-control input-md",
			                 name => "arrowstreamid",
			                 # required => "required",
			               },
			      title => "ArrowStream ID",
			      type => "textfield",
			      val => undef,
			},			
			parentid => {
			      attrs => {
			                 class => "form-control input-md",
			                 name => "parentid",
			                 required => "required",
			               },
			      title => "Group",
			      type => "textfield",
			      val => undef,
			},
			chaingroupid => {
			      attrs => {
			                    class => "input-md form-control",
			                    name => "chaingroupid",
			                    required => "required",
			                  },
			      default => undef,
			      labels => [],
			      # populate => {
			      #               defaults => "chaingroup",
			      #               labels => "chaingroupname",
			      #               vals => "chaingroupid",
			      #               data => ['chaingroupvp','chaingrouppam']
			      #             },
			      populate => {
			                    # defaults => "user",
			                    defaults => {
			                    	module => "ChainGroup",
			                    	options => {
						                prefetch => [],			                    		
			                    		order_by => "chaingroupname"
			                    	},

			                    	# fk => 'id',
			                    	where => [qw/active/],
			                    	vals => [1],			                    	

			                    },			                    
			                    labels => 'chaingroupname',
			                    # sub {
			                    # 	my ($el,$dv) = (@_);
			                    # 	return sprintf("%s - %s %s - %s", $dv->{iacctnmbr} || 'N/A', $dv->{fname}, $dv->{lname}, $dv->{company});
			                    # },
			                    vals => "chaingroupid",
			                    data => ['chaingroupvp','chaingrouppam'],
			                  },			      
			      title => "Chain Group",
			      type => "select",
			      vals => [],
			      data => []
			    },			
    	},
	};

	my $aform = dclone $fform;
	$aform->{attrs}->{name} = $c->module() . 'addform';
	$aform->{attrs}->{formon} = 'form-always';
	$aform->{attrs}->{formoff} = 'form-never';

	$c->{_forms}->{default} = $c->form($fform);
	$c->{_forms}->{add} = $c->form($aform);

	$c->{_buttongroup}->{add} = $c->form([
			{
				type => 'buttongroup',
				attrs => [{
					class => 'btn btn-success',
					name => 'add',
					type => 'button'
				},					
				],
				labels => ["Add Record"],
			},
	]);


	$c->{_buttongroup}->{default} = $c->form([
			# {
			# 	type => 'buttongroup',
			# 	class => 'form-never',
			# 	attrs => [{
			# 		class => 'btn btn-warning form-never',
			# 		name => 'edit',
			# 		type => 'button'
			# 	},	
			# 	{
			# 		class => 'btn btn-danger form-never',
			# 		name => 'delete',
			# 		type => 'button'
			# 	},							
			# 	],
			# 	labels => ["Edit","Delete"],
			# 	# vals => [qw/save reset/],
			# },		
		    {
				type => 'buttongroup',
				class => 'form-always',
				attrs => [{
					class => 'btn btn-success',
					name => 'save',
					type => 'button'
				},
				{
					class => 'btn btn-default ',
					name => 'close',
					type => 'button',
					'data-dismiss' => 'modal'
				},
				{
					class => 'btn btn-danger',
					name => 'delete',
					type => 'button'
				},				
				],
				labels => ["Save","Close","Delete"],
				# vals => [qw/save reset/],
			},

	]);

}

1;
