import os
import c4d
from ssp_ids import *


def GetIconImage(idIconOrBl2d, factor=None):
    if type(idIconOrBl2d) == int:
        icon = c4d.gui.GetIcon(idIconOrBl2d)

    else:
        icon = idIconOrBl2d.GetIcon()

    if icon is not None:
        bmpIcon = icon['bmp'].GetClonePart(icon['x'], icon['y'], icon['w'], icon['h'])

    else:
        bmpIcon = None
        PrintError('Icon not found ({0})'.format(idIconOrBl2d))

    if factor is not None:
        bmpIcon = ScaleImage(bmpIcon, factor=factor)

    return bmpIcon


def LoadImage(filename, subfolder='img', suffix='.png'):
    filename = filename + suffix
    imgPath = os.path.join(os.path.dirname(__file__), subfolder, filename)

    bmp = c4d.bitmaps.BaseBitmap()
    result = bmp.InitWith(imgPath)

    if result[0] != c4d.IMAGERESULT_OK:
        print('{0} ERROR: Failed to load image: {1}'.format(PLUGIN_NAME, filename))
        return None

    return bmp


def ScaleImage(bmp, w=100, h=100, factor=0):
    if factor != 0:
        w, h = bmp.GetSize()
        w = int(w * factor)
        h = int(h * factor)

    bmpScaled = c4d.bitmaps.BaseBitmap()

    bmpScaled.Init(w, h)

    bmp.ScaleIt(bmpScaled, 256, True, False)

    return bmpScaled

def BlendPixel(bmpTarget, r, g, b, a, xTarget, yTarget):
    rTarget, gTarget, bTarget = bmpTarget.GetPixel(xTarget, yTarget)

    rTarget = int(rTarget * (1.0 - a)) + int(r * a)
    gTarget = int(gTarget * (1.0 - a)) + int(g * a)
    bTarget = int(bTarget * (1.0 - a)) + int(b * a)

    bmpTarget.SetPixel(xTarget, yTarget, rTarget, gTarget, bTarget)


def FadeImageToBackground(bmp, fade):
    fade = fade / 100.0

    colorBg = c4d.gui.GetGuiWorldColor(c4d.COLOR_BG) * 255
    rBg = colorBg.x
    gBg = colorBg.y
    bBg = colorBg.z

    w, h = bmp.GetSize()

    for y in range(h):
        for x in range(w):
            BlendPixel(bmp, rBg, gBg, bBg, fade, x, y)
