/*
 * Jalview - A Sequence Alignment Editor and Viewer (2.11.1.3)
 * Copyright (C) 2020 The Jalview Authors
 * 
 * This file is part of Jalview.
 * 
 * Jalview is free software: you can redistribute it and/or
 * modify it under the terms of the GNU General Public License 
 * as published by the Free Software Foundation, either version 3
 * of the License, or (at your option) any later version.
 *  
 * Jalview is distributed in the hope that it will be useful, but 
 * WITHOUT ANY WARRANTY; without even the implied warranty 
 * of MERCHANTABILITY or FITNESS FOR A PARTICULAR 
 * PURPOSE.  See the GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with Jalview.  If not, see <http://www.gnu.org/licenses/>.
 * The Jalview Authors are detailed in the 'AUTHORS' file.
 */
package jalview.io;

import static org.testng.AssertJUnit.assertEquals;
import static org.testng.AssertJUnit.assertNotNull;
import static org.testng.AssertJUnit.assertTrue;

import jalview.bin.Cache;
import jalview.datamodel.AlignmentAnnotation;
import jalview.datamodel.AlignmentI;
import jalview.datamodel.PDBEntry;
import jalview.datamodel.SequenceFeature;
import jalview.datamodel.SequenceI;
import jalview.datamodel.features.SequenceFeatures;
import jalview.gui.AlignFrame;
import jalview.gui.JvOptionPane;
import jalview.structure.StructureImportSettings;
import jalview.structure.StructureImportSettings.StructureParser;

import java.io.File;
import java.util.List;

import org.junit.Assert;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

public class AnnotatedPDBFileInputTest
{

  @BeforeClass(alwaysRun = true)
  public void setUpJvOptionPane()
  {
    JvOptionPane.setInteractiveMode(false);
    JvOptionPane.setMockResponse(JvOptionPane.CANCEL_OPTION);
  }

  AlignmentI al;

  String pdbId;

  /**
   * Ensure 'process secondary structure from PDB and add annotations' are set
   * in preferences, and load PDB example file 1gaq
   * 
   * @throws Exception
   */
  @BeforeMethod(alwaysRun = true)
  public void setup() throws Exception
  {
    Cache.applicationProperties.setProperty("STRUCT_FROM_PDB",
            Boolean.TRUE.toString());
    Cache.applicationProperties.setProperty("ADD_SS_ANN",
            Boolean.TRUE.toString());
    FileLoader loader = new FileLoader(false);
    AlignFrame af = loader.LoadFileWaitTillLoaded("examples/1gaq.txt",
            DataSourceType.FILE);
    al = af.getViewport().getAlignment();
    pdbId = al.getSequenceAt(0).getDatasetSequence().getAllPDBEntries()
            .get(0).getId();
    StructureImportSettings.setDefaultStructureFileFormat("PDB");
    // StructureImportSettings
    // .setDefaultPDBFileParser(StructureParser.JALVIEW_PARSER);
  }

  @Test(groups = { "Functional" })
  public void checkNoDuplicates()
  {
    // not strictly a requirement, but strange things may happen if multiple
    // instances of the same annotation are placed in the alignment annotation
    // vector
    assertNotNull(al.getAlignmentAnnotation());
    // verify that all sequence annotation is doubly referenced
    AlignmentAnnotation[] avec = al.getAlignmentAnnotation();
    for (int p = 0; p < avec.length; p++)
    {
      for (int q = p + 1; q < avec.length; q++)
      {
        assertTrue("Found a duplicate annotation row " + avec[p].label,
                avec[p] != avec[q]);
      }
    }
  }

  @Test(groups = { "Functional" }, enabled = false)
  public void checkPDBannotationSource()
  {
    Assert.fail(
            "This test is incorrect - does not verify that JmolParser's annotation rows can be recognised as generated by the Jmol parser.");
    for (SequenceI asq : al.getSequences())
    {
      for (AlignmentAnnotation aa : asq.getAnnotation())
      {

        System.out.println("CalcId: " + aa.getCalcId());
        if (StructureImportSettings.getDefaultPDBFileParser()
                .equals(StructureParser.JALVIEW_PARSER))
        {
          assertTrue(MCview.PDBfile.isCalcIdForFile(aa, pdbId));
        }
      }
    }
  }

  /**
   * Check sequence features have been added
   */
  @Test(groups = { "Functional" })
  public void checkPDBSequenceFeatures()
  {
    /*
     * 1GAQ/A
     */
    List<SequenceFeature> sf = al.getSequenceAt(0).getSequenceFeatures();
    SequenceFeatures.sortFeatures(sf, true);
    assertEquals(296, sf.size());
    assertEquals("RESNUM", sf.get(0).getType());
    assertEquals("GLU:  19  1gaqA", sf.get(0).getDescription());
    assertEquals("RESNUM", sf.get(295).getType());
    assertEquals("TYR: 314  1gaqA", sf.get(295).getDescription());

    /*
     * 1GAQ/B
     */
    sf = al.getSequenceAt(1).getSequenceFeatures();
    SequenceFeatures.sortFeatures(sf, true);
    assertEquals(98, sf.size());
    assertEquals("RESNUM", sf.get(0).getType());
    assertEquals("ALA:   1  1gaqB", sf.get(0).getDescription());
    assertEquals("RESNUM", sf.get(97).getType());
    assertEquals("ALA:  98  1gaqB", sf.get(97).getDescription());

    /*
     * 1GAQ/C
     */
    sf = al.getSequenceAt(2).getSequenceFeatures();
    SequenceFeatures.sortFeatures(sf, true);
    assertEquals(296, sf.size());
    assertEquals("RESNUM", sf.get(0).getType());
    assertEquals("GLU:  19  1gaqC", sf.get(0).getDescription());
    assertEquals("RESNUM", sf.get(295).getType());
    assertEquals("TYR: 314  1gaqC", sf.get(295).getDescription());
  }

  @Test(groups = { "Functional" })
  public void checkAnnotationWiring()
  {
    assertTrue(al.getAlignmentAnnotation() != null);
    // verify that all sequence annotation is doubly referenced
    for (AlignmentAnnotation aa : al.getAlignmentAnnotation())
    {
      if (aa.sequenceRef != null)
      {
        assertTrue(al.getSequences().contains(aa.sequenceRef));
        assertNotNull(aa.sequenceRef.getAnnotation());
        boolean found = false;
        for (AlignmentAnnotation sqan : aa.sequenceRef.getAnnotation())
        {
          if (sqan == aa)
          {
            found = true;
            break;
          }
        }
        assertTrue(
                "Couldn't find sequence associated annotation "
                        + aa.label
                        + " on the sequence it is associated with.\nSequence associated editing will fail.",
                found);
      }
    }
  }

  /**
   * @throws java.lang.Exception
   */
  @BeforeClass(alwaysRun = true)
  public static void setUpBeforeClass() throws Exception
  {
    jalview.bin.Jalview.main(new String[] { "-props",
        "test/jalview/io/testProps.jvprops" });
  }

  /**
   * @throws java.lang.Exception
   */
  @AfterClass(alwaysRun = true)
  public static void tearDownAfterClass() throws Exception
  {
    jalview.gui.Desktop.instance.closeAll_actionPerformed(null);

  }

  @Test(groups = { "Functional" })
  public void testJalviewProjectRelocationAnnotation() throws Exception
  {

    String inFile = "examples/1gaq.txt";
    String tfile = File.createTempFile("JalviewTest", ".jvp")
            .getAbsolutePath();
    AlignFrame af = new jalview.io.FileLoader().LoadFileWaitTillLoaded(
            inFile, DataSourceType.FILE);
    assertTrue("Didn't read input file " + inFile, af != null);
    assertTrue("Failed to store as a project.",
            af.saveAlignment(tfile, FileFormat.Jalview));
    af.closeMenuItem_actionPerformed(true);
    af = null;
    af = new jalview.io.FileLoader().LoadFileWaitTillLoaded(tfile,
            DataSourceType.FILE);
    assertTrue("Failed to import new project", af != null);
    for (SequenceI asq : af.getViewport().getAlignment().getSequences())
    {
      SequenceI sq = asq;
      while (sq.getDatasetSequence() != null)
      {
        sq = sq.getDatasetSequence();
      }
      assertNotNull(sq.getAllPDBEntries());
      assertEquals("Expected only one PDB ID", 1, sq.getAllPDBEntries()
              .size());
      for (PDBEntry pdbentry : sq.getAllPDBEntries())
      {
        System.err.println("PDB Entry " + pdbentry.getId() + " "
                + pdbentry.getFile());
        boolean exists = false, found = false;
        for (AlignmentAnnotation ana : sq.getAnnotation())
        {
          System.err.println("CalcId " + ana.getCalcId());
          if (ana.getCalcId() != null
                  && MCview.PDBfile.isCalcIdHandled(ana.getCalcId()))
          {
            exists = true;
            if (MCview.PDBfile.isCalcIdForFile(ana, pdbentry.getId()))
            {
              found = true;
            }
          }
        }
        if (exists)
        {
          assertTrue("Couldn't find any annotation for " + pdbentry.getId()
                  + " (file handle " + pdbentry.getFile() + ")", found);
        }
      }
    }
  }
}
