#!/usr/bin/env python
import os
import sys
import argparse
import warnings

import pandas as pd

from plio.io.io_bae import read_atf, read_gpf, read_ipf
import plio.io.io_controlnetwork as cn
import plio.io.isis_serial_number as sn
from plio.spatial.transformations import apply_socet_transformations
from plio.utils.utils import split_all_ext

def parse_args():
    parser = argparse.ArgumentParser()

    parser.add_argument('at_file', help='Path to the .atf file for a project.')
    parser.add_argument('cub_list', help='Path to a list file containing paths to the associated\
                                                                 Isis cubes.')
    parser.add_argument('target_name', help='Name of the target body used in the control net')
    parser.add_argument('--outpath', help='Directory for the control network to be output to.')

    return parser.parse_args()


def main(args):
    # Setup the at_file, path to cubes, and control network out path
    at_file = args.at_file

    with open(args.cub_list, 'r') as f:
        lines = f.readlines()
        cub_list = [cub.replace('\n', '') for cub in lines]

    cnet_out = os.path.split(os.path.splitext(at_file)[0])[1]

    if( args.outpath ):
        outpath = args.outpath
    else:
        outpath = os.path.split(at_file)[0]

    # Read in and setup the atf dict of information
    atf_dict = read_atf(at_file)

    # Get the gpf and ipf files using atf dict
    gpf_file = os.path.join(atf_dict['PATH'], atf_dict['GP_FILE']);
    ipf_list = [os.path.join(atf_dict['PATH'], i) for i in atf_dict['IMAGE_IPF']]

    # Read in the gpf file and ipf file(s) into seperate dataframes
    gpf_df = read_gpf(gpf_file)
    ipf_df = read_ipf(ipf_list)

    # Check for differences between point ids using each dataframes
    # point ids as a reference
    gpf_pt_idx = pd.Index(pd.unique(gpf_df['point_id']))
    ipf_pt_idx = pd.Index(pd.unique(ipf_df['pt_id']))

    point_diff = ipf_pt_idx.difference(gpf_pt_idx)

    if len(point_diff) != 0:
        warnings.warn("The following points found in ipf files missing from gpf file: \n\n{}. \
                      \n\nContinuing, but these points will be missing from the control network".format(list(point_diff)))

    # Merge the two dataframes on their point id columns
    socet_df = ipf_df.merge(gpf_df, left_on='pt_id', right_on='point_id')

    # Apply the transformations
    apply_socet_transformations(atf_dict, socet_df)

    # Define column remap for socet dataframe
    column_map = {'pt_id': 'id', 'l.': 'y', 's.': 'x',
                               'res_l': 'lineResidual', 'res_s': 'sampleResidual', 'known': 'Type',
                               'lat_Y_North': 'aprioriY', 'long_X_East': 'aprioriX', 'ht': 'aprioriZ',
                               'sig0': 'aprioriLatitudeSigma', 'sig1': 'aprioriLongitudeSigma', 'sig2': 'aprioriRadiusSigma',
                               'sig_l': 'linesigma', 'sig_s': 'samplesigma'}

    # Rename the columns using the column remap above
    socet_df.rename(columns = column_map, inplace=True)

    # Build a serial dict assuming the cubes will be named as the IPFs are
    serial_dict = {split_all_ext(os.path.split(i)[-1]): sn.generate_serial_number(i) for i in cub_list}

    # creates the control network
    cn.to_isis(os.path.join(outpath, cnet_out + '.net'), socet_df, serial_dict, targetname = args.target_name)

if __name__ == '__main__':
    main(parse_args())
