package CLMApp::Controller::ChainGroup;
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 Groups',
	table => 'ChainGroup',
	module => 'chaingroup',
	pk => 'chaingroupid',
	columns => [qw/active chaingroupid chaingroupname chaingroupamphireid chaingroupvp chaingrouppam chaingroupnotes bpstorefrontcode arrowstreamid invoicesystem ordersystem/],
	prefetch => ['vp','programmanager'],
	order_by => ['me.chaingroupname']
};

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 ($frm,$butt) = $c->populate_form('add');

	$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({params => $p, table=> $c->table, order_by => $c->order_by, sort => 'desc', group_by => [$c->pk], columns => $c->columns, prefetch => $c->prefetch});
	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 setup{
	my $c = shift;


	my $fform = {
		attrs => {
			name => 'chaingroupform',
			onsubmit => 'javascript: return false;',
			title => '',
			action => '',
			method => 'POST',
			formon => 'form-always',
			formoff => 'form-never',
			cols => 1,
			autocomplete=>"new-password"
		},
		sorder => [],
		eorder => [qw/active chaingroupid chaingroupname chaingroupamphireid arrowstreamid invoicesystem ordersystem chaingroupvp chaingrouppam bpstorefrontcode chaingroupnotes/],
		elems =>     {
			active => {
			      attrs => { class => "", name => "active" },
				  labels => ['Enabled'],			      
				  title => "Active",
			      type => "checkbox",
			      vals => [1],
			      default => undef
			},			
			chaingroupid => {
			      attrs => { class => "form-control input-md", name => "chaingroupid" },
			      title => "ID",
			      type => "hidden",
			      val => undef,
			},
			chaingroupname => {
			      attrs => {
			                 class => "form-control input-md",
			                 name => "chaingroupname",
			                 required => "required",
			               },
			      title => "Name",
			      type => "textfield",
			      val => undef,
			},
			chaingroupamphireid => {
			      attrs => {
			                 class => "form-control input-md",
			                 name => "chaingroupamphireid",
			                 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,
			},			
			# chaingroupvp => {
			#       attrs => {
			#                  class => "form-control input-md",
			#                  name => "chaingroupvp",
			#                  required => "required",
			#                },
			#       title => "DMA VP",
			#       type => "textfield",
			#       val => undef,
			# },
			# chaingrouppam => {
			#       attrs => {
			#                  class => "form-control input-md",
			#                  name => "chaingrouppam",
			#                  required => "required",
			#                },
			#       title => "DMA SCS",
			#       type => "textfield",
			#       val => undef,
			# },


			invoicesystem => {
			      attrs => {
			                    class => "input-md form-control",
			                    # disabled => "disabled",
			                    name => "invoicesystem",
			                  },
			      default => undef,
			      labels => [],
			      populate => {
			                    # defaults => "dmaprogrammanager",
					      		# defaults => "dmavp", 
					            defaults => {
					                    	module => "OrderInvoiceSystem",
					                    	options => {
					                    		order_by => "systemname",
					                    		# select => [qw/dmaprogrammanagerid dmaprogrammanager/],
					                    		# as => [qw/chaingrouppam dmaprogrammanager/]
					                    	},
					                    	# fk => 'id',
					                    	where => [qw/invoicesystem/],
					                    	vals => [1],
					             },
			                    labels => "systemname",
			                    vals => "id",
								data => ["id"]

			       },
			      title => "Invoice System",
			      type => "select",
			      vals => [],
			      data => []
			},
			ordersystem => {
			      attrs => {
			                    class => "input-md form-control",
			                    # disabled => "disabled",
			                    name => "ordersystem",
			                  },
			      default => undef,
			      labels => [],
			      populate => {
			                    # defaults => "dmaprogrammanager",
					      		# defaults => "dmavp", 
					            defaults => {
					                    	module => "OrderInvoiceSystem",
					                    	options => {
					                    		order_by => "systemname",
					                    		# select => [qw/dmaprogrammanagerid dmaprogrammanager/],
					                    		# as => [qw/chaingrouppam dmaprogrammanager/]
					                    	},
					                    	# fk => 'id',
					                    	where => [qw/ordersystem/],
					                    	vals => [1],
					             },
			                    labels => "systemname",
			                    vals => "id",
								data => ["id"]

			       },
			      title => "Order System",
			      type => "select",
			      vals => [],
			      data => []
			},

			chaingrouppam => {
			      attrs => {
			                    class => "input-md form-control",
			                    # disabled => "disabled",
			                    name => "chaingrouppam",
			                  },
			      default => undef,
			      labels => [],
			      populate => {
			                    # defaults => "dmaprogrammanager",
					      		# defaults => "dmavp", 
					            defaults => {
					                    	module => "DmaprogramManager",
					                    	options => {
					                    		order_by => "dmaprogrammanager",
					                    		select => [qw/dmaprogrammanagerid dmaprogrammanager/],
					                    		as => [qw/chaingrouppam dmaprogrammanager/]
					                    	},
					                    	# fk => 'id',
					                    	where => [qw//],
					                    	vals => [],
					             },
			                    labels => "dmaprogrammanager",
			                    vals => "chaingrouppam",
								data => ["chaingrouppam"]

			                  },
			      title => "DMA SCS",
			      type => "select",
			      vals => [],
			      data => []
			    },
			'chaingroupvp' => {
			      attrs => {
			                    class => "input-md form-control",
			                    # disabled => "disabled",
			                    name => "chaingroupvp",
			                  },
			      default => undef,
			      labels => [],
			      populate => { 
			      		defaults => "dmavp", 
			                    defaults => {
			                    	module => "Dmavp",
			                    	options => {
			                    		order_by => "dmavp",
			                    		select => [qw/dmavpid dmavp/],
			                    		as => [qw/chaingroupvp dmavp/]
			                    	},
			                    	# fk => 'id',
			                    	where => [qw//],
			                    	vals => [],
			                    },				      		
						labels => "dmavp", 
						vals => "chaingroupvp",
						data => ["chaingroupvp"]
			       },
			      title => "DMA VP",
			      type => "select",
			      vals => [],
			      data => []
			    },


			# chaingrouppam => {
			#       attrs => {
			#                     class => "input-md form-control",
			#                     name => "chaingrouppam",
			#                     required => "required",

			#                   },
			#       default => undef,
			#       labels => [],
			#       populate => {
			#                     defaults => "dmaprogrammanager",
			#                     labels => "dmaprogrammanager",
			#                     vals => "dmaprogrammanagerid",
			#                   },
			#       title => "DMA SCS",
			#       type => "select",
			#       vals => [],
			#     },
			# chaingroupvp => {
			#       attrs => {
			#                     class => "input-md form-control",
			#                     name => "chaingroupvp",
			# 	                 required => "required",

			#                   },
			#       default => undef,
			#       labels => [],
			#       populate => { defaults => "dmavp", labels => "dmavp", vals => "dmavpid" },
			#       title => "DMA VP",
			#       type => "select",
			#       vals => [],
			#     },	
			bpstorefrontcode => {
			      attrs => {
			                 class => "form-control input-md",
			                 name => "bpstorefrontcode",
			               },
			      title => "StoreFront Code",
			      type => "textfield",
			      val => undef,
			},
			chaingroupnotes => {
			      attrs => {
			                 class => "form-control input-md",
			                 name => "chaingroupnotes",
			               },
			      title => "Notes",
			      type => "textarea",
			      val => undef,
			}								
    	},
	};

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

	$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;


1;