########################################################################
#
#TASK XML> tclean -argfilter=interactive,fullsummary,outlierfile
# Copyright (C) 2024
# Associated Universities, Inc. Washington DC, USA.
#
# This script is free software; you can redistribute it and/or modify it
# under the terms of the GNU Library General Public License as published by
# the Free Software Foundation; either version 2 of the License, or (at your
# option) any later version.
#
# This library 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 Library General Public
# License for more details.
#
# You should have received a copy of the GNU Library General Public License
# along with this library; if not, write to the Free Software Foundation,
# Inc., 675 Massachusetts Ave, Cambridge, MA 02139, USA.
#
# Correspondence concerning AIPS++ should be adressed as follows:
#        Internet email: aips2-request@nrao.edu.
#        Postal address: AIPS++ Project Office
#                        National Radio Astronomy Observatory
#                        520 Edgemont Road
#                        Charlottesville, VA 22903-2475 USA
#
########################################################################
##################### generated by xml-casa (v2) from {{name}}.xml
##################### {{md5}} ##############################
from __future__ import absolute_import
from casashell.private.stack_manip import find_local as __sf__
from casashell.private.stack_manip import find_frame as _find_frame
from casatools.typecheck import validator as _pc
from casatools.coercetype import coerce as _coerce
from casatools.errors import create_error_string
from casatasks.private.task_logging import start_log as _start_log
from casatasks.private.task_logging import end_log as _end_log
from casagui.apps import InteractiveClean
from collections import OrderedDict
import numpy
import sys
import os

import shutil

def static_var(varname, value):
    def decorate(func):
        setattr(func, varname, value)
        return func
    return decorate


def _iclean_t( *args, **kwargs ):
    ic = InteractiveClean( *args, **kwargs )
    return ic( )


class _iclean:
    """
{{docstring}}
    """

    _info_group_ = """{{group}}"""
    _info_desc_ = """{{desc}}"""

    __schema = { {{# paramListNKW}}'{{name}}': {{schema}}, {{/ paramListNKW}} }

    def __init__(self):
        self.__stdout = None
        self.__stderr = None
        self.__root_frame_ = None

    def __globals_(self):
        if self.__root_frame_ is None:
            self.__root_frame_ = _find_frame( )
            assert self.__root_frame_ is not None, "could not find CASAshell global frame"
        return self.__root_frame_

    def __to_string_(self,value):
        if type(value) is str:
            return "'%s'" % value
        else:
            return str(value)

    def __validate_(self,doc,schema):
        return _pc.validate(doc,schema)

    def __do_inp_output(self,param_prefix,description_str,formatting_chars):
        out = self.__stdout or sys.stdout
        description = description_str.split( )
        prefix_width = 23 + 23 + 4
        output = [ ]
        addon = ''
        first_addon = True
        if len(description) == 0:
            out.write(param_prefix + " #\n")
            return
        while len(description) > 0:
            ## starting a new line.....................................................................
            if len(output) == 0:
                ## for first line add parameter information............................................
                if len(param_prefix)-formatting_chars > prefix_width - 1:
                    output.append(param_prefix)
                    continue
                addon = param_prefix + ' #'
                first_addon = True
                addon_formatting = formatting_chars
            else:
                ## for subsequent lines space over prefix width........................................
                addon = (' ' * prefix_width) + '#'
                first_addon = False
                addon_formatting = 0
            ## if first word of description puts us over the screen width, bail........................
            if len(addon + description[0]) - addon_formatting + 1 > self.term_width:
                ## if we're doing the first line make sure it's output.................................
                if first_addon: output.append(addon)
                break
            while len(description) > 0:
                ## if the next description word puts us over break for the next line...................
                if len(addon + description[0]) - addon_formatting + 1 > self.term_width: break
                addon = addon + ' ' + description[0]
                description.pop(0)
            output.append(addon)
        out.write('\n'.join(output) + '\n')

    #--------- go functions -----------------------------------------------------------
{{# paramList}}{{goDefault}}

{{goValue}}

{{goInp}}

{{/ paramList}}
    #--------- global default implementation-------------------------------------------
    @static_var('state', __sf__('casa_inp_go_state'))
    def set_global_defaults(self):
        self.set_global_defaults.state['last'] = self
        glb = self.__globals_( ){{# paramList}}
        if '{{name}}' in glb: del glb['{{name}}']{{/ paramList}}

    #--------- inp function -----------------------------------------------------------
    def inp(self):
        print("# iclean -- %s" % self._info_desc_)
        self.term_width, self.term_height = shutil.get_terminal_size(fallback=(80, 24)){{# paramList}}
        self.__{{name}}_inp( ){{/ paramList}}

    #--------- tget function ----------------------------------------------------------
    @static_var('state', __sf__('casa_inp_go_state'))
    def tget(self,savefile=None):
        from runpy import run_path
        filename = savefile
        if filename is None:
            filename = "iclean.last" if os.path.isfile("iclean.last") else "iclean.saved"
        if os.path.isfile(filename):
            glob = _find_frame( )
            newglob = run_path( filename, init_globals={ } )
            for i in newglob:
                glob[i] = newglob[i]
            self.tget.state['last'] = self
        else:
            print("could not find last file: %s\nsetting defaults instead..." % filename)
            self.set_global_defaults( )

    #--------- tput function ----------------------------------------------------------
    def tput(self,outfile=None):
        def noobj(s):
           if s.startswith('<') and s.endswith('>'):
               return "None"
           else:
               return s

        _postfile = outfile if outfile is not None else os.path.realpath('iclean.last')

        _invocation_parameters = OrderedDict( ){{# paramList}}
        _invocation_parameters['{{name}}'] = self.__{{name}}( self.__globals_( ) ){{/ paramList}}

        try:
            with open(_postfile,'w') as _f:
                for _i in _invocation_parameters:
                    _f.write("%-20s = %s\n" % (_i,noobj(repr(_invocation_parameters[_i]))))
                _f.write("#iclean( ")
                count = 0
                for _i in _invocation_parameters:
                    _f.write("%s=%s" % (_i,noobj(repr(_invocation_parameters[_i]))))
                    count += 1
                    if count < len(_invocation_parameters): _f.write(",")
                _f.write(" )\n")
        except: return False
        return True

    def __call__( self{{# paramList}}, {{name}}=None{{/ paramList}} ):
        def noobj(s):
           if s.startswith('<') and s.endswith('>'):
               return "None"
           else:
               return s
        _prefile = os.path.realpath('iclean.pre')
        _postfile = os.path.realpath('iclean.last')
        task_result = None
        _arguments = [{{# paramList}}{{name}},{{/ paramList}}]
        _invocation_parameters = OrderedDict( )
        if any(map(lambda x: x is not None,_arguments)):
            # invoke python style
            # set the non sub-parameters that are not None
            local_global = { }{{# paramListNonSub}}
            if {{name}} is not None: local_global['{{name}}'] = {{name}}{{/ paramListNonSub}}

            # the invocation parameters for the non-subparameters can now be set - this picks up those defaults{{# paramListNonSub}}
            _invocation_parameters['{{name}}'] = self.__{{name}}( local_global ){{/ paramListNonSub}}

            # the sub-parameters can then be set. Use the supplied value if not None, else the function, which gets the appropriate default{{# paramListSub}}
            _invocation_parameters['{{name}}'] = self.__{{name}}( _invocation_parameters ) if {{name}} is None else {{name}}{{/ paramListSub}}

        else:
            # invoke with inp/go semantics{{# paramList}}
            _invocation_parameters['{{name}}'] = self.__{{name}}( self.__globals_( ) ){{/ paramList}}
        try:
            with open(_prefile,'w') as _f:
                for _i in _invocation_parameters:
                    _f.write("%-20s = %s\n" % (_i,noobj(repr(_invocation_parameters[_i]))))
                _f.write("#iclean( ")
                count = 0
                for _i in _invocation_parameters:
                    _f.write("%s=%s" % (_i,noobj(repr(_invocation_parameters[_i]))))
                    count += 1
                    if count < len(_invocation_parameters): _f.write(",")
                _f.write(" )\n")
        except: pass
        try:
            _logging_state_ = None
            assert _pc.validate(_invocation_parameters,self.__schema), create_error_string(_pc.errors)
            _logging_state_ = _start_log( 'iclean', [{{# paramList}} '{{name}}=' + repr(_pc.document['{{name}}']),{{/ paramList}} ] )
            task_result = _iclean_t( {{# paramList}}{{name}}=_pc.document['{{name}}'],{{/ paramList}} )
        except Exception as e:
            from traceback import format_exc
            from casatasks import casalog
            casalog.origin('iclean')
            casalog.post("Exception Reported: Error in iclean: %s" % str(e),'SEVERE')
            casalog.post(format_exc( ))
            raise #exception is now raised
            #task_result = False
        finally:
            try:
                os.rename(_prefile,_postfile)
            except: pass
            if _logging_state_:
                task_result = _end_log( _logging_state_, 'iclean', task_result )

        #Added if _iclean_t returns False and does not raise an exception.
        if task_result is False:
            raise

        return task_result #Still needed

iclean = _iclean( )
