# -*- coding: utf-8 -*-

"""RancidCmd."""

from subprocess import Popen
from subprocess import PIPE
import os
import stat


class RancidCmd(object):

    """Class RancidCmd.

    Attributes:

        :login (str): RANCID login command(clogin, jlogin, etc).
        :user (str): Login username.
        :password (str): Login password.
        :address (str): Host name or address.
        :enable_password (str, optional): Enable password for clogin.
            Default is None.
        :timeout(int, optional): Timeout value(seconds).
            Default is 10 seconds.
        :encoding(str, optional): Encoding type.
            Default is 'utf-8'.

    Using example:

        * Please see README.
            https://github.com/mtoshi/rancidcmd/blob/master/README.rst

        * Sample code.
            https://github.com/mtoshi/rancidcmd/blob/master/samples/sample.py

    """

    def __init__(self, **kwargs):
        """Constructor.

        Args:

        :login (str): RANCID login command(clogin, jlogin, etc).
        :user (str): Login username.
        :password (str): Login password.
        :address (str): Host name or address.
        :enable_password (str, optional): Enable password for clogin.
            Default is None.
        :timeout(int, optional): Timeout value(seconds).
            Default is 10 seconds.
        :encoding(str, optional): Encoding type.
            Default is 'utf-8'.

        """
        self.login = kwargs['login']
        self.user = kwargs['user']
        self.password = kwargs['password']
        self.address = kwargs['address']
        self.enable_password = kwargs.get('enable_password', None)
        self.timeout = kwargs.get('timeout', 10)
        self.encoding = 'utf-8'
        RancidCmd.check_cloginrc()

    def generate_cmd(self, command):
        """Make login command."""
        if self.enable_password:
            return '%s -t %s -u "%s" -p "%s" -e "%s" -c "%s" %s' % (
                self.login, self.timeout, self.user,
                self.password, self.enable_password, command, self.address)
        return '%s -t %s -u "%s" -p "%s" -c "%s" %s' % (
            self.login, self.timeout, self.user,
            self.password, command, self.address)

    def decode_bytes(self, byte_data):
        """Change string with encoding setting."""
        return byte_data.decode(self.encoding)

    def cmd_exec(self, command):
        """Login and command execution."""
        proc = Popen(command,
                     shell=True,
                     stdout=PIPE,
                     stderr=PIPE)
        std_out, std_err = proc.communicate()
        return {'std_out': self.decode_bytes(std_out),
                'std_err': self.decode_bytes(std_err)}

    def execute(self, command):
        """Command execution."""
        cmd = self.generate_cmd(command)
        return self.cmd_exec(cmd)

    @staticmethod
    def touch(path):
        """Make empty file."""
        try:
            with open(path, 'a'):
                os.utime(path, None)
                os.chmod(path, stat.S_IRUSR | stat.S_IWUSR | stat.S_IXUSR)
        except:
            print('[error] Could not write "%s".' % path)
            raise

    @staticmethod
    def check_cloginrc(name='.cloginrc'):
        """Check rancid settings file (default: .cloginrc)."""
        home = os.environ['HOME']
        path = '%s/%s' % (home, name)
        if not os.path.isfile(path):
            RancidCmd.touch(path)
        return path

@@ -953,32 +953,36 @@
  Args:%0A%0A        
+    
 :login (str): RA
@@ -1014,32 +1014,36 @@
 , jlogin, etc).%0A
+    
         :user (s
@@ -1063,32 +1063,36 @@
 ername.%0A        
+    
 :password (str):
@@ -1108,32 +1108,36 @@
 ssword.%0A        
+   
+ 
 :address (str): 
@@ -1150,32 +1150,36 @@
 ame or address.%0A
+    
         :enable_
@@ -1236,32 +1236,36 @@
 in.%0A            
+   
+ 
 Default is None.
@@ -1257,32 +1257,36 @@
 efault is None.%0A
+    
         :timeout
@@ -1330,32 +1330,36 @@
 s).%0A            
+  
+  
 Default is 10 se
@@ -1357,32 +1357,36 @@
  is 10 seconds.%0A
+    
         :encodin
@@ -1410,32 +1410,36 @@
  Encoding type.%0A
+    
             Defa
@@ -1859,27 +1859,461 @@
  %22%22%22
-Make login command.
+Generate command.%0A%0A        Args:%0A%0A            :command (str): Example is %22show version%22.%0A%0A        Returns:%0A%0A            :str: Return the command string.%0A%0A            If there is the %22enable_password%22. ::%0A%0A                'clogin -t 10 -u admin -p password -e enable_password%0A                    -c %22show version%22'%0A%0A            If you have not set the %22enable_password%22. ::%0A%0A                'clogin -t 10 -u admin -p password -c %22show version%22'%0A%0A        
 %22%22%22%0A
@@ -3255,32 +3255,263 @@
 mmand execution.
+%0A%0A        Args:%0A%0A            :command (str): Example is %22show version%22.%0A%0A        Returns:%0A%0A            :dict: Example is below. ::%0A%0A            %7B%0A                'std_err': '',%0A                'std_out': '',%0A            %7D%0A%0A        
 %22%22%22%0A        cmd 

Add docstring.