import os
import time

from crossnetwork_processing_functions import set_file_permissions_ownership, create_GHOST_stage_logfile

class Zip:

    '''Class which zips entire network tree of compressed netCDF files into one .zip file'''
    
    def __init__(self, region, run_details, parameter_details, network_details):

        #add passed variables to self
        self.region = region
        self.run_details = run_details
        self.parameter_details = parameter_details
        self.network_details = network_details

        self.run_details['log_file_str'] += 'ZIPPING NETWORK\n'

    def do_work(self):
        '''Function which does executes the functions of the class in a pipeline'''

        #create monthly netCDF
        self.zip()

    def zip(self):
        '''Function which zips entire network tree of compressed netCDF files into one .zip file'''

        #set network directory where to read/write data
        if self.region == 'GLOBAL':
            network_write_dir = self.run_details['network']
        else:
            network_write_dir = '{}_{}'.format(self.run_details['network'], self.region)

        #set zip filename
        zip_fname = '{}.zip'.format(network_write_dir)

        #save current directory
        current_dir = os.getcwd()

        #change directory to directory to just outside the component directory to zip 
        os.chdir("{}GHOST_v{}".format(self.run_details['compress_root'], self.run_details['ghost_version']))
        
        #zip directory
        os.system("zip -r -m {} {}".format(zip_fname, network_write_dir))

        #give 770 permissions for file and make owner bsc32
        set_file_permissions_ownership(zip_fname)   
        
        #return to original directory
        os.chdir(current_dir)

        #return valid process logfile (0)
        self.run_details['log_file_str'] += str((time.time() - self.run_details['stage_process_start_time'])/60.)
        create_GHOST_stage_logfile(0,self.run_details)