#!/usr/bin/env python
#-*- coding: UTF-8 -*-

__author__ = 'helljump'

import logging
import grab
import pycurl
import os
from pytils.translit import slugify
from ZODB.utils import p64
import re
import transaction


log = logging.getLogger(__name__)


class Uploader(object):

    img_re = re.compile('(cm3\://image/(\d+))')

    def __init__(self, proxy=None, connection=None):
        self.g = grab.Grab()
        if __name__ == '__main__':
            self.g.setup(log_dir='dump')
        self.g.setup(hammer_mode=True)
        if proxy:
            self.g.load_proxylist(proxy, 'text_file', auto_init=True, auto_change=True)
        self.conn = connection

    def mimer(self, fname):
        ext = os.path.splitext(fname.lower())
        exts = {
            ".jpg": "image/jpeg",
            ".jpeg": "image/jpeg",
            ".png": "image/png",
            ".gif": "image/gif"
        }
        return exts.get(ext, "image/jpeg")

    def upload_doc(self, doc):
        done = 0
        for row in self.img_re.findall(doc.text):
            url, oid = row
            obj = self.conn.get(p64(int(oid)))
            data = obj.data.open('r').read()
            if data[1:4] == 'PNG':
                fn = slugify(doc.title) + '.png'
            else:
                fn = slugify(doc.title) + '.jpg'
            newurl = self.upload(fn, data)
            log.debug('upload %s -> %s', url, newurl)
            doc.text = doc.text.replace(url, newurl)
            done += 1
        return done

    def upload(self, fname, data):
        self.g.setup(
            referer='http://savepic.su/index.php',
            multipart_post=[
                ('subm', u'Отправить'.encode('cp1251')),
                ('file"; filename="%s' % fname, (pycurl.FORM_CONTENTS, data, pycurl.FORM_CONTENTTYPE, self.mimer(fname))),
                ('email', ''),
                ('opt3[]', 'zoom'),
                ('note', ''),
                ("font1", 'decor'),
                ("font2", '20'),
                ("orient", 'h'),
                ("size1", 'x'),
                ("size2", '1024x768'),
                ("rotate", '00'),
                ("flip", '0'),
                ('mini', '300x225'),
            ],
        )
        self.g.go('http://savepic.su/index.php')
        try:
            return self.g.doc.select('//input[@id="http"]/@value').text()
        except grab.error.DataNotFound:
            raise Exception(u'Ошибка выгрузки. Причина может быть в БАНе вашего ip, либо неисправном прокси.')


if __name__ == '__main__':
    data = open(r'd:\work2014\cm3\_test\images\armiya-prizvala-egiptyan-razojtis-po-domam.jpg', 'rb').read()
    up = Uploader()
    print up('test.jpg', data)
