#######################################################################
# this software has been created by Genome Research Limited (GRL).    # 
# GRL hereby grants permission to use, copy, modify and distribute    # 
# this software and its documentation for non-commercial purposes     # 
# without fee at the user's own risk on the basis set out below.      #
# GRL neither undertakes nor accepts any duty whether contractual or  # 
# otherwise in connection with the software, its use or the use of    # 
# any derivative, and makes no representations or warranties, express #
# or implied, concerning the software, its suitability, fitness for   #
# a particular purpose or non-infringement.                           #
# In no event shall the authors of the software or GRL be responsible # 
# or liable for any loss or damage whatsoever arising in any way      # 
# directly or indirectly out of the use of this software or its       # 
# derivatives, even if advised of the possibility of such damage.     #
# Our software can be freely distributed under the conditions set out # 
# above, and must contain this copyright notice.                      #
#######################################################################

package Draw_Contig;

use Tk;
use Tk::Dialog;
use Tk::ErrorDialog;
require Qplot;
require ByTempl;
require ListPick;
# Globals

my $FONT = '8x13';
my $FONTs = '6x10';
my %ContObjs;
my %Boundarys;
my $IW;
my $arrx;

############################################################################################################
sub ContigInfo{
  my ($c,$contig) = @_;
  my @Table;   
  my $t;
  my $y= 20;
  my $canv;

  if(&InfoWin::Create_InfoWin)
  {
     # &InfoWin::ClearWin;
      
      my $canv = &InfoWin::GetInfoCanv;
      
      if($canv)
      {
	  &InfoWin::FillList(&ByTempl::ReadTable($contig));
	  		 
      }				 
       
  }				
}
#########################################################################################################################
sub NearBoundary{

    my($x) = @_;
    my @n = grep(($x == $_),@Boundarys);
    $n[0];
}
sub GetBoundary{
    my($c) = @_;
    my @bbox;
    my @Assem = &ByTempl::Get_ContigOrd;
    undef(%Boundarys);

    foreach (@Assem)
    {
	@bbox = $c->bbox($_);
#        $CBs{$_}->[0] = $bbox[0];
#	$CBs{$_}->[1] = $bbox[2];
        my $mid = int($bbox[0] + (($bbox[2] - $bbox[0])/2));
        $Boundarys{$mid} = $_;	
      
    }
   
}
############################################################################################################
sub Draw_Contig{
  
   my ($c,$y,$xxt,$yxt,$end) = @_;
   my $line;
   my %cord ;
   my @Assem = &ByTempl::Get_ContigOrd;
   my %CComp = &ByTempl::Get_ContComp;
   my $x;
   my $x2;
   my $name;
   my $oname = "";
   my $x3;
   my $down = 15;
   my $num;
   my $lastx;
   my $maxy = 0;
   my @tbox;
   my $id;

   &Qplot::Set_xxt_yxt($xxt,$yxt); # mapping parameters
   $x = Qplot::dmapx(1,$end,0);	   # start position
   $lastx = $x;
   %cord = &ByTempl::Calc_offsets(@Assem);   # start coords
   undef(@Boundarys);
   undef(%CBs);
   push(@Assem,"end");

   foreach $line (@Assem)	
   {				# 
       my $nname = $oname;   
       $name = $cord{$line};	# $line = name of contig
       $x2 = Qplot::dmapx($name,$end,0);
       $x3 = int(($x2-$x)/2) + $x;
       my %iinfo = ();
       $iinfo{'areaX1'} = 0;
       $iinfo{'areaY1'} = 0;
       $iinfo{'areaX2'} = 0;
       $iinfo{'areaY2'} = 0;
       $iinfo{'restore_cmd'} = '';

       $c->create('line' ,$x3, $y+10 , $x3, $y + $down, -width =>1, -fill => 'light blue');
       $c->create('text', $x3, $y + $down , -text => $oname, -font => $FONTs,-fill => 'black');
       $id = $c->create('oval',$x2,$y-10 ,$x,$y+10,-width=> 2,-outline => 'black',-fill=> 'white');
       push(@Boundarys,$x2,$x);
#       push(@{$CBs{$oname}},$x2,$x); 
       $c->dtag($oname);
       $c->addtag($oname, withtag => $id);

       $c->bind($id,'<Any-Enter>' => [\&ContigInfo,$oname]);

       $c->bind($id,'<1>' => sub {
	   my($c) = @_;
	   my $e = $c->XEvent;
	   &items_start_drag ($c, $e->x, $e->y, \%iinfo);
       });

       $c->bind($id,'<B1-Motion>' => sub {
	   my($c) = @_;
	   my $e = $c->XEvent;
	   &items_drag ($c, $e->x, $e->y, \%iinfo);
       });
       $c->bind($id,'<B1-ButtonRelease>' => sub {
	   my($c) = @_;
	   my $e = $c->XEvent;
	   &items_drop ($c, $e->x, $e->y, $nname, \%iinfo);
       });

       my $comp = $CComp{$oname};
       my $arrowwidth = abs($x - $x2);
       $arrowwidth = 10 if($arrowwidth > 10);
       my @ids;
       if($comp == 1){ 
	  
	   $ids[0] = $c->create('polygon',$x3,$y-10,$x3,$y-20,$x3+$arrowwidth,$y-15,$x3,$y-10,
				-width=>1,-outline=>'black',-fill=> 'green');
	   $ids[1] = $c->create('polygon',$x3,$y-10,$x3,$y-20,$x3-$arrowwidth,$y-15,$x3,$y-10,
				-width=>1,-outline=>'black',-fill=> 'red');
       }
       else {
	 
	   $ids[0] = $c->create('polygon',$x3,$y-10,$x3,$y-20,$x3+$arrowwidth,$y-15,$x3,$y-10,
				-width=>1,-outline=>'black',-fill=> 'red');
	   $ids[1] = $c->create('polygon',$x3,$y-10,$x3,$y-20,$x3-$arrowwidth,$y-15,$x3,$y-10,
				-width=>1,-outline=>'black',-fill=> 'green');
       }
       $c->bind($ids[0],'<Button-1>' => [\&ByTempl::RevComp,$oname]);
       $c->bind($ids[1],'<Button-1>' => [\&ByTempl::RevComp,$oname]);
       $x = $x2;
       $down += 10;
       if(($y + $down) > $maxy) { $maxy = ($y + $down);}
       if(($x - $lastx) >= 80){$down = 15; $lastx = $x;}
       $oname = $line;   
       $c->update;
   }
   $x2 = Qplot::dmapx($end,$end,0);
   &GetBoundary($c);
   $c->create('line', $x, $y, $x2, $y, -width => 2,-fill => 'blue');
   $maxy += 20;
   $maxy;
}

sub items_start_drag {

    my($c, $x, $y, $iinfo) = @_;

    $iinfo->{'lastX'} = $c->canvasx($x);
    $iinfo->{'lastY'} = $c->canvasy($y);

} # end items_start_drag

sub items_drag {

    my($c, $x, $y, $iinfo) = @_;

    # scroll right or left
    my @xv = $c->xview;
    my $marg = ($xv[1] - $xv[0]) /10; 
    my $left = $xv[0] + $marg ;
    my $right = $xv[1] - $marg ;
    
    my $mid = $left + (($right-$left)/2);
    my @bb;

    $x = $c->canvasx($x);
    $y = $c->canvasy($y);
   
    my $xp = $x / (&main::GetXXT);

    if($xp > $right)
    {				# 
	$c->xview(scroll => 1, 'unit');

    }elsif($xp < $left)
    {
	$c->xview(scroll => -1, 'unit');

    }
    $c->move('current', $x-$iinfo->{'lastX'}, $y-$iinfo->{'lastY'});
    $iinfo->{'lastX'} = $x;
    $iinfo->{'lastY'} = $y;

    &DArrow($c,$x,250); 
    $arrx = $x;
    				
} # end items_drag
sub by_num{
    $a <=> $b;
}
sub items_drop {

    my($c, $x, $y,$cont, $iinfo) = @_;

    $arrx = $c->canvasx($x);
 

    if(!defined($arrx)){return;}
    &main::Wait('New Contig Order');

    my @conts;
    my @Assem = &ByTempl::Get_ContigOrd;
    my $l = $#Assem;
    my $k;

    my @pos = sort by_num keys(%Boundarys); 
    $l = $#pos;

    for($k=0; $k < $l; $k++)
    {
	#print "$pos[$k]  $arrx  $pos[($k+1)] \n";
	if(($pos[$k] <= $arrx) && ($pos[($k+1)] >= $arrx))
	{
	    push(@conts,$Boundarys{$pos[$k]});
	    if(($Boundarys{$pos[$k]} eq $cont) || ($Boundarys{$pos[($k+1)]} eq $cont)){&main::Done;return;}
	    last;
	}

    }
    return if($#conts < 0);
   
    my $i=0;
    foreach (@Assem)
    {
	if($_ eq $cont){splice(@Assem,$i,1);last;}
	$i++;
    }
    $i=0;
    push(@conts,$cont);
    foreach (@Assem)
    {
	if($_ eq $conts[0]){splice(@Assem,$i,1,@conts);last;}
	$i++;
    }
    
    &ByTempl::NewContOrder(@Assem);
    &main::Done;
    &main::Draw_Reads;
   
} # end items_drag

sub DArrow{
    my($c , $x , $y) = @_;
    $c->delete('posarrow');
    my $id = $c->create('line', $x, $y - 25, $x,$y, -width => 2,-arrow => 'last' ,-fill => 'red');
    $c->addtag('posarrow', withtag => $id);
}
######################################################################################################
sub FindContig{
    my ($c) = @_;
    my $picked;
   
    my @list = sort &ByTempl::Get_ContigOrd;
    $picked = &ListPick::ListPick(&main::GetMW,'Pick the Contig you wish to find ',@list);
    my @bbox = (0,0,0,0);
   
    if($picked eq "") {return @bbox;}
 
    @bbox = $c->bbox($picked); 

    @bbox;

}
######################################################################################################
sub Draw_keylabel{

 my ($c,$y1,$y2,$text,$col) = @_;
 my $len = length($text);
 my @ids;

 if(defined($y1) && defined($y2))
 {
     my $start = int(abs($y2 - $y1)/10)+$y1;
     my $i;
     my $scalfact = ($start+($len *8));
   
     $ids[0] = $c->create('line', 30, $y1, 30,$y2, -width => 2,-fill => $col);
     $ids[1] = $c->create('line', 30, $y1, 35,$y1, -width => 2,-fill => $col);
     $ids[2] = $c->create('line', 30, $y2, 35,$y2, -width => 2,-fill => $col);
 
 if($scalfact <= $y2)
 {
    for($i=0; $i<$len; $i++)
    {
     $ids[3+$i] = $c->create('text',10,$start+(8 * $i), -text => substr($text,$i,1), -font => $FONTs, -fill => 'blue');
     }
  }
 }

 @ids;

}
###########################################################################################################

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

###########################################################################################################
1;
