import Image from '../image';

export default function bitDepth(newBitDepth) {

    this.checkProcessable('bitDepth', {
        bitDepth: [8,16]
    });

    if (! [8,16].contains(newBitDepth)) throw Error('You need to specify the new bitDepth as 8 or 16')

    if (newBitDepth === 8) {
        if (this.bitDepth === 8) {
            return this.clone();
        }

        let newImage = Image.createFrom(this, {
            bitDepth: 8
        });

        let data = this.data;
        for (let i = 0; i < this.data.length; i++) {
            newImage.data[i] = data[i] >> 8;
        }

        return newImage;
    }

    if (newBitDepth === 16) {
        this.checkProcessable('bitDepth', {
            bitDepth: [8,16]
        });

        if (this.bitDepth === 16) {
            return this.clone();
        }

        let newImage = Image.createFrom(this, {
            bitDepth: 16
        });

        let data = this.data;
        for (let i = 0; i < this.data.length; i++) {
            newImage.data[i] = data[i] << 8;
        }

        return newImage;
    }



}

@@ -126,32 +126,33 @@
    bitDepth: %5B8,
+ 
 16%5D%0A    %7D);%0A%0A   
@@ -161,23 +161,22 @@
 f (!
- 
 %5B8,16%5D.
-contain
+include
 s(ne
@@ -249,16 +249,17 @@
  or 16')
+;
 %0A%0A    if
@@ -252,36 +252,38 @@
  16');%0A%0A    if (
-newB
+this.b
 itDepth === 8) %7B
@@ -282,59 +282,20 @@
 === 
-8) %7B%0A        if (this.bitDepth === 8) %7B%0A           
+newBitDepth)
  ret
@@ -312,35 +312,21 @@
 lone();%0A
-        %7D%0A%0A 
+%0A
     
-   
 let newI
@@ -360,75 +360,62 @@
 s, %7B
-%0A            bitDepth: 8%0A        %7D);%0A%0A        let data = this.data;
+bitDepth: newBitDepth%7D);%0A%0A    if (newBitDepth === 8) %7B
 %0A   
@@ -487,32 +487,37 @@
 Image.data%5Bi%5D = 
+this.
 data%5Bi%5D %3E%3E 8;%0A  
@@ -528,352 +528,20 @@
   %7D%0A
-%0A        return newImage;%0A    %7D%0A%0A    if (newBitDepth === 16) %7B%0A        this.checkProcessable('bitDepth', %7B%0A            bitDepth: %5B8,16%5D%0A        %7D);%0A%0A        if (this.bitDepth === 16) %7B%0A            return this.clone();%0A        %7D%0A%0A        let newImage = Image.createFrom(this, %7B%0A            bitDepth: 16%0A        %7D);%0A%0A        let data = this.data;
+    %7D else %7B
 %0A   
@@ -621,16 +621,21 @@
 ta%5Bi%5D = 
+this.
 data%5Bi%5D 
@@ -650,21 +650,23 @@
       %7D%0A
-%0A
     
+%7D%0A%0A
     retu
@@ -682,15 +682,6 @@
 ge;%0A
-    %7D%0A%0A%0A%0A
 %7D%0A

refactor bitDepth method