#!/usr/bin/python

##
## Copyright (C) 2011-2012 Andrew Atkinson
##
##-------------------------------------------------------------------
## This program 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.
##
## This program 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 this program.  If not, see <http://www.gnu.org/licenses/>.
##-------------------------------------------------------------------

#python modules
import os
#import re
import shutil
#import subprocess
#import sys
#import threading
import wx

#Program modules
import CheckerCreate
import ReadTop
import relshots
import Writeth
import Writeth2
import Writethconfig


def Run(settings, cavers):
    ##Check for spaces in top file and raw location, which will break things
    #if re.search(r"\s", settings['pockettopo']):
        #message = settings['pockettopo'] +
        #'''\n has spaces in it, please correct'''
        #if re.search(r"\s", settings['rawdir']):
            #message += '/nand/n' + settings['rawdir'] +
            #'\n has spaces in it, please correct'
    #elif re.search(r"\s", settings['rawdir']):
        #message += settings['rawdir'] + '\n has spaces in it, please correct'
    #

    #Check the top file location is actually a file
    if not os.path.isfile(settings['pockettopo']):
        message = settings['pockettopo'] + '''\n is not a file.'''
        dlg = wx.MessageDialog(None, message, 'PocketTop File',
                               style=wx.OK | wx.ICON_ERROR)
        temp = dlg.ShowModal()
        return

    #The project root must exist, other directories can be created
    if not os.path.exists(settings['projectroot']):
        message = settings['projectroot'] + '''
does not exist.
Topparser will not create this for you.
        '''
        dlg = wx.MessageDialog(None, message, 'Project Directory',
                               style=wx.OK | wx.ICON_ERROR)
        temp = dlg.ShowModal()
        return

    #Put a status box or something in here

    #Assemble the directories, survey names for use
    locations = {}
    topfilename = os.path.basename(settings['pockettopo'])
    locations['surveyname'] = os.path.splitext(topfilename)[0]
    locations['surveydir'] = os.path.join(settings['projectroot'],
                                            settings['surveydir'])
    if settings['addnamedir']:
        locations['surveydir'] = os.path.join(locations['surveydir'],
                                                locations['surveyname'])
    if settings['insurveydir']:
        locations['rawdir'] = os.path.join(locations['surveydir'],
                                settings['rawdir'])
    else:
        locations['rawdir'] = os.path.join(settings['projectroot'],
                    settings['rawdir'])

    #make the directories, add to repository for svn
    #These should raise errors if fail
    for dir in [locations['surveydir'], locations['rawdir']]:
        CheckerCreate.Structure(dir)
        if (settings['add2rep'] & (settings['repository'] == 'svn')):
            CheckerCreate.ShellCall(settings['repository'] + ' add \"' +
            dir + '\"')
    #copy top file
    topfile = os.path.join(locations['rawdir'], topfilename)
    if settings['copytop']:
        name = os.path.basename(topfile)
        if settings['pockettopo'] != topfile:
            copyfile = settings['overwrite'] | (not(os.path.exists(topfile)))
            if not copyfile:
                message = name + ''' already exists.
    Would you like to overwrite.
    (No, will skip the file)'''
                dlg = wx.MessageDialog(None, message, 'Existing file',
                                       style=wx.YES_NO)
                temp = dlg.ShowModal()
                if temp == wx.ID_YES:
                    copyfile = True
                else:
                    print('Not written file ' + name)
                dlg.Destroy()
            if copyfile:
                #do I really want copy2 or just copy!!!
                shutil.copy2(settings['pockettopo'], locations['rawdir'])
                print('Copied top file')
                if (settings['add2rep'] & (settings['repository'] == 'svn')):
                    CheckerCreate.ShellCall(settings['repository'] + ' add \"' +
                    topfile + '\"')
            #Really need an error check here, to see if it is actually added
                    print('Top file added to repository')
        else:
            print(name + ': Source and destination the same. Skipping copy!')

    #If only doing config file do not need to read or calculate data
    if (settings['dothfile'] | settings['dosvxfile'] | settings['doplan']
                | settings['doelevation'] | settings['doprojection']):
        #Read the file
        try:
            topodata = ReadTop.readfile(settings['pockettopo'],
                                        settings['doplan'],
                                        settings['doelevation'])
            print('Successfully read file')
        except():
            #Dialog box needed
            print('Something went wrong reading the file')

        #Output the th file and get the relative positions
        try:
            shots2 = Writeth.therionfile(topodata, settings, cavers, locations)
            if settings['dothfile']:
                print('Written ' + locations['surveyname'] +
                        '.th and calculated realtive positions')
            else:
                print('Calculated realtive positions')
        except:
            print('Something went wrong when using the Data (Writeth)')
            raise

    if settings['doplan'] | settings['doelevation'] | settings['doprojection']:
        relcoor = relshots.relshots(shots2, topodata,
                                    settings['doplan'],
                                    settings['doelevation'],
                                    settings['projangle'])

        #Output plan (th2 file)
        if settings['doplan']:
            Writeth2.th2plan(relcoor, settings, topodata['outline'],
                             relcoor['startstn'], locations, 'plan')
#            print('Writen plan th2 file: '
#                  + locations['surveyname'] + settings['plansuffix'] + '.th2')

        #Output extended elevation (th2 file)
        if settings['doelevation']:
            Writeth2.th2elev(relcoor, settings, topodata['sideview'],
                             relcoor['startstn'], locations, 'elev')
#            print('Writen elevation th2 file: '
#                  + locations['surveyname'] + settings['elevsuffix'] + '.th2')

        #Output projected elevation (th2 file)
        if settings['doprojection']:
            filesuffix = settings['projsuffix'].replace('###',
                                                    str(settings['projangle']))
            scrapsuffix = settings['pescrapsuffix'].replace('###',
                                                    str(settings['projangle']))
            #if settings['anglesuffixfile']:
                #filesuffix = settings['projsuffix'] +
                                                    #str(settings['projangle'])
            #else:
                #filesuffix = settings['projsuffix']
            #if settings['anglesuffixscrap'] == True:
                #scrapsuffix = settings['pescrapsuffix'] +
                                            #str(settings['projangle']) + '_'
            #else:
                #scrapsuffix = settings['pescrapsuffix']
            Writeth2.th2file('proj', locations, filesuffix,
                                settings['projscale'], settings['projDPI'],
                                relcoor['stnpos'], relcoor['startstn'],
                                settings['projgrid'],
                                settings,
                                pangle=settings['projangle'],
                                ins_scraps=settings['pescraps'],
                                scrapsuffix=scrapsuffix)
#            print('Writen projection th2 file: '
#                  + locations['surveyname'] + filesuffix + '.th2')

    #output thconfig
    if settings['dothconfig']:
        Writethconfig.writethconfig(settings, locations)
#        print('Produced config file: ' + settings['configname'])

    #Process data
    cfile = os.path.join(locations['surveydir'], settings['configname'])
    if settings['process']:
        #check for thconfig file
        if os.path.isfile(cfile):
            try:
                print('Therion Output\n==============')
                CheckerCreate.ShellCall(settings['therion'] + ' \"' +
                                        cfile + '\"',
                                        locations['surveydir'])
#                os.system(settings['therion'] + ' ' + cfile)
                print('Data processed')
            except:
                print('Could not process data')
        else:
            print(settings['configname'], "does not exist, cannot process data")

    #open 3d
    if settings['open3d']:
        fname = (os.path.join(locations['surveydir'],
                                       locations['surveyname'] +
                                       settings['dsuffix'] + '.3d'))
        if os.path.isfile(fname):
            viewercom = settings[settings['viewer']]
            try:
                CheckerCreate.ShellCall(viewercom + ' \"' + fname + '\"',
                                        locations['surveydir'])
#                os.system(viewercom + ' \"' + fname)
            except:
                print('Something went wrong while opening '
                      + settings['viewer'])
        else:
            print(fname + ' does not exist, cannot display 3d')

    #open xtherion files
    if settings['openfiles']:
        # make files with full paths to be opened
        print('Preparing to open files')
        thname = locations['surveyname'] + '.th'
        thpath = os.path.join(locations['surveydir'], thname)
        if settings['th2edit'] == 'xplan':
            th2name = locations['surveyname'] + settings['plansuffix'] + '.th2'
        else:
            th2name = locations['surveyname'] + settings['elevsuffix'] + '.th2'
        th2path = os.path.join(locations['surveydir'], th2name)
        # If the chosen th2 does not exist try the other
        if not os.path.isfile(th2path):
            if settings['th2edit'] == 'xelev':
                th2name = (locations['surveyname'] +
                           settings['plansuffix'] + '.th2')
            else:
                th2name = (locations['surveyname'] +
                           settings['elevsuffix'] + '.th2')
            th2path = os.path.join(locations['surveydir'], th2name)
        # Put together the command
        com = settings['xtherion']
        if os.path.isfile(thpath):
            com += ' \"' + os.path.abspath(thpath) + '\"'
        else:
            print(thname + ' does not exist to open')
        if os.path.isfile(cfile):
            com += ' \"' + os.path.abspath(cfile) + '\"'
        else:
            print(settings['configname'] + ' does not exist to open')
        if os.path.isfile(th2path):
            com += ' \"' + os.path.abspath(th2path) + '\"'
        else:
            print(th2name + ' does not exist to open')
        if com != settings['xtherion']:
            try:
#                os.system(com)
                CheckerCreate.ShellCall(com, locations['surveydir'])
            except:
                print('Something went wrong while trying to open xtherion')
        else:
            print('Cannot open xtherion: No files exist')
