import { IpcRenderer } from "electron/renderer";
import { PatternOutput } from "../patterns/proto";

import './patterns.css';

const ipcRenderer = (window as any).electron.ipcRenderer as IpcRenderer;

const PatternPreview: React.FC<{ patternId: string, output: PatternOutput , selected: boolean}> = ({ patternId, output, selected}) => {
  const selectedClass = selected ? " selected" : "";
  const styleClass = "pattern-button" + selectedClass;
  return <div style={{ margin: 5 }}>
    <svg className={styleClass}/*style={{ padding: 15, backgroundColor: "#333333", borderColor: "white", borderRadius: 15 }}*/ onClick={() =>
      ipcRenderer.send("pattern-select", patternId)
    } width={260 + 2*70} height="150">
      {output?.map((headState, index) => {
        const [r, g, b, w] = headState.rgbw;
        const brightness = "value" in headState.brightness ? headState.brightness.value : 0;
        return <ColorCone tilt={headState.tilt} pan={headState.pan} white={w} color={`rgba(${r},${g},${b},${(0.3 + 0.7 * brightness)})`} translate={[70 + index * 65, 0]} />
      }
      )}
    </svg>
  </div>
}

const ColorCone: React.FC<{ pan: number, tilt: number, color: string, translate: [number, number], white: number}> = ({ color, translate: [x, y], white, pan, tilt }) => {
  return <g transform={`translate(${x} ${y})`}>
    {white === 0 ? null
      : <Cone pan={pan} tilt={tilt} color={`rgba(1, 1, 1, ${white}`} translate={[x, y]} />
    }
    <Cone pan={pan} tilt={tilt} color={color} translate={[x, y]} />
  </g>
};


const Cone: React.FC<{ color: string, translate: [number, number] , pan : number, tilt: number}> = ({ color , tilt, pan}) => {
  // tilt is correct with -45 degree offset, but if lights are pointing down, they will be displayed to point down right
  const degreesTilt = tilt / (2* Math.PI) * 360 - 45;
  // TODO: adjust if necessary
  const degreesPan = pan / (2* Math.PI) * 360 - 45;

  console.log(degreesTilt);
  return <g className="cone" style={{transform: `rotate(${degreesTilt}deg) rotateX(${degreesPan}deg)`}} >
    <path stroke="black" fill="gray" d="M 15 0 L 45 0 L 60 30 L 0 30 L 15 0" />
    <path fill={color} d="M 15 30 L 0 150 L 60 150 L 45 30 " />
  </g>;
};

export default PatternPreview;
