#!/usr/local/nzbconfig/env/bin/python
import os
import tempfile
import shutil
import subprocess
import pwd
import configobj
import ConfigParser
from pyextdirect.configuration import create_configuration, expose, LOAD, SUBMIT


Base = create_configuration()


SABNZBD = 'sabnzbd'
NZBGET = 'nzbget'
UNDEFINED = 'nochange'


class SABnzbd(Base):
    var_path = '/usr/local/sabnzbd/var'
    config_path = os.path.join(var_path, 'config.ini')
    sickbeard_postprocessing_dir = '/usr/local/sickbeard/share/SickBeard/autoProcessTV'
    sickbeard_postprocessing_filenames = ['sabToSickBeard.py', 'autoProcessTV.cfg', 'autoProcessTV.py']
    sickbeardcustom_postprocessing_dir = '/usr/local/sickbeard-custom/var/SickBeard/autoProcessTV'
    sickbeardcustom_postprocessing_filenames = ['sabToSickBeard.py', 'autoProcessTV.cfg', 'autoProcessTV.py']

    def __init__(self):
        self.config = None
        if os.path.exists(self.config_path):
            self.config = configobj.ConfigObj(self.config_path)

    @expose
    def is_installed(self):
        return self.config is not None

    @expose(kind=LOAD)
    def load(self):
        if self.config is None:
            return None
        return {'sickbeard_postprocessing': self.sickbeard_postprocessing_configured(), 'sickbeardcustom_postprocessing': self.sickbeardcustom_postprocessing_configured()}

    @expose(kind=SUBMIT)
    def save(self, sickbeard_postprocessing=None, sickbeardcustom_postprocessing=None):
        if sickbeard_postprocessing:
            self.sickbeard_postprocessing_enable()
        else:
            self.sickbeard_postprocessing_disable()
        if sickbeardcustom_postprocessing:
            self.sickbeardcustom_postprocessing_enable()
        else:
            self.sickbeardcustom_postprocessing_disable()

    def sickbeard_postprocessing_configured(self):
        script_dir = self.get_script_dir()
        configured = True
        for filename in self.sickbeard_postprocessing_filenames: