#!/usr/local/bin/perl
package anchorview;

# Form-processing script that takes parameters from mapview
# and passes the appropriate URL to contigview or cytoview
# (or throws an error back to mapview!)

use strict;

use CGI;
use URI::Escape qw(uri_escape);
use EnsEMBL::Web::Factory::Location;

my $hub           = new EnsEMBL::Web::Hub;
my $species_defs  = $hub->species_defs;
my $species_path  = $species_defs->species_path;
my $factory       = new EnsEMBL::Web::Factory::Location({
    _hub           => $hub,
    _input         => $hub->input,
    _apache_handle => $hub->apache_handle,
    _databases     => $hub->databases,
    _core_objects  => $hub->core_objects,
    _parent        => $hub->parent,
});


eval {
  $factory->createObjects;
};

my $extra_url;

foreach (qw(type1 anchor1 type2 anchor2 downstream upstream chr)) {
  $extra_url .= sprintf ';%s=%s', $_, uri_escape($hub->param($_)) if $hub->param($_);
}

if ($hub->has_problem_type('fatal')) {
  $hub->redirect("$species_path/Location/Chromosome?error=1$extra_url");
} elsif ($hub->has_a_problem) {
  $hub->redirect("$species_path/Location/Chromosome?error=2$extra_url"); ## this means not all on same chromosome
} else { ## grab the object and check to see if it is less than 5Mb
  my $object = $factory->object; 
  my $script = $object->length < 1.0001e6 * ($species_defs->ENSEMBL_GENOME_SIZE || 1) ? 'contigview' : 'cytoview';
     $script = 'cytoview' if $species_defs->NO_SEQUENCE;
     
  my $url = sprintf(
    '%s/%s?l=%s:%d-%s',
    $species_path,
    $script,
    $object->seq_region_name,
    $object->seq_region_start,
    $object->seq_region_end
  );
  
  $url .= ';h=' . join('|', 
    ($object->param('type1') eq 'bp' ? () : $object->param('anchor1')),
    ($object->param('type2') eq 'bp' ? () : $object->param('anchor2'))
  );
  
  $hub->redirect($url);
}

1;
